package CtrLayer;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;

import ModelLayer.*;
import DBLayer.*;

public class CtrRentalPayment {
	
	private IFDBRentalPayment dbRP;
	Calendar cal = Calendar.getInstance();
	
	public CtrRentalPayment(){
		dbRP = DBRentalPayment.getInstance();
	}

	public ArrayList<RentalPayment> getAll(){
		return dbRP.getAll();
		
	}
	
	public double getCommissionLastMonth(){
		return dbRP.getCommissionLastMonth();
	}
	
	public double getCommissionThisMonth(){
		return dbRP.getCommissionThisMonth();
	}
	
	public double getReceivable(){
		return dbRP.getReceivable();
	}
	
	public ArrayList<RentalPayment> getAll_where(String wClause){
		return dbRP.getAll_where(wClause);
		
	}
	
	public ArrayList<RentalPayment> searchRandom(String searchF){
		return dbRP.searchRandom(searchF);
	}
	
	public RentalPayment getRentalPaymentById(int paymentID){
		return dbRP.getRentalPaymentById(paymentID);
		
	}
	
	public int insert(int paymentID, Timestamp date, double amount, Apartment apartment){
		return dbRP.insert(new RentalPayment(paymentID, date, amount, apartment));
	}
	
	public int insertPayment(Timestamp date, double amount, int apartId)
	{		
		Contract contr = DBContract.getInstance().getContract_byApartId(apartId);
		if(contr.getTenant().getPid() == 0) return -1;	// there is no contract for this apartment
		
		cal.setTime(date);
		
		double monthlyRent = contr.getApartment().getMonthlyRent();
		int tenantId = contr.getTenant().getPid();
		
		while(amount > 0)
		{
			RentalPayment rpD = dbRP.getRentalPayment_byDateAndApartment(apartId, date);

			double thisMonthDB = rpD.getAmount();
			double thisMonthRequired = monthlyRent - thisMonthDB;
			
			if(thisMonthRequired > amount) thisMonthRequired = amount;
			
			if(thisMonthRequired>0)
			{
				dbRP.insert(date, thisMonthRequired, apartId, tenantId);				
				amount = amount - thisMonthRequired;
			}
			
			cal.set(Calendar.DAY_OF_MONTH, 1);
			cal.add(Calendar.MONTH, 1);
			date = new Timestamp(cal.getTime().getTime());
	
		}
		
		System.out.println();
		
		return 1;
	}
	
	
	public int update(int paymentID, Timestamp date, double amount, Apartment apartment){
		return dbRP.update(new RentalPayment(paymentID, date, amount, apartment));
	}
	
	public int delete(int paymentID){
		return dbRP.delete(paymentID);
	}
}
